package org.achao.redis;

import lombok.extern.slf4j.Slf4j;
import org.achao.server.RedisWebSocketDemoServer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 消息监听对象，接收订阅消息
 */
@Slf4j
@Component
@SuppressWarnings(value = {"rawtypes"})
public class RedisMessageListener implements MessageListener {

    @Resource
    public RedisTemplate redisTemplate;

    @Resource
    private RedisWebSocketDemoServer webSocketServer;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] body = message.getBody();
        // 使用序列化转换器
        Object msg = redisTemplate.getValueSerializer().deserialize(body);
        // 获取监听频道
        byte[] msgChannel = message.getChannel();
        // 使用字符串序列器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(msgChannel);
        // 渠道名称转换
        String patternStr = new String(pattern);
        if (StringUtils.isNotEmpty((String) msg)){
            log.info("redis-> --频道--: {}",channel);
            log.info("redis-> --消息--: {}",msg);
            if (RedisMsgListenerContainer.PRIVATE_MSG.endsWith(patternStr)) {
                log.info("私聊");
                webSocketServer.privateMsg((String) msg);
            } else {
                // TODO
                log.info("群聊");
            }
        }else {
            log.info("消息内容为空，不处理。");
        }
    }
}
